<template>
  <div>
    <vxe-modal
      :title="$t('common.title.upload')"
      v-model="show"
      :loading="loading"
      :mask="false"
      :lock-view="false"
      width="500"
      height="300"
      destroy-on-close
      show-zoom
      remember
      resize
      show-footer
    >
      <div class="image-list" style="width: 100%">
        <el-upload
          v-loading="loading"
          action="#"
          ref="uploadRef"
          :http-request="handleUpload"
          :on-exceed="handleOnExceed"
          :show-file-list="false"
          :multiple="multiple"
          :limit="limit"
        >
          <template #tip>
            <div class="el-upload__tip">
              {{ $t('common.message.upload.browse') }}
            </div>
          </template>
          <el-button type="primary" icon="Upload">
            {{ $t('common.action.upload') }}
          </el-button>
        </el-upload>
        <ul class="el-upload-list el-upload-list--text">
          <li
            v-for="(item, i) in imageList"
            :key="i"
            class="el-upload-list__item is-success"
          >
            <div style="display: flex; justify-content: space-between">
              <div>
                <span
                  style="cursor: pointer"
                  @click="handlePictureCardPreview(item.url)"
                >
                  <el-icon><Document /></el-icon>
                  {{ item.url }}
                </span>
              </div>
              <div>
                <span style="margin-right: 20px; cursor: pointer">
                  <el-icon @click.stop="handleRemove(item.id)"
                    ><Close
                  /></el-icon>
                </span>
              </div>
            </div>
          </li>
        </ul>
      </div>
      <!-- 页脚部分 -->
      <template #footer>
        <el-button type="info" icon="Close" @click="closeUploadModal">
          {{ $t('common.action.close') }}
        </el-button>
      </template>
    </vxe-modal>
    <!-- 图片预览 -->
    <el-image-viewer
      v-if="viewVisible"
      :zoom-rate="1.2"
      :initial-index="initialIndex"
      :url-list="viewFileList"
      @close="closePreview"
    />
  </div>
</template>
<script setup>
/**
 * 这是一个通用的，可以上传任意类型文件的组件，用于文件管理器
 */
import { smartTranslate as $t } from '@/lang';
import AdminFileAPI from '@/api/admin/admin/file';

const props = defineProps({
  multiple: {
    type: Boolean,
    default: true,
  },
  limit: {
    type: Number,
    default: 99,
  },
});

const emit = defineEmits(['reload']);
const show = ref(false);
const uploadRef = ref();
const imageList = ref([]);
const loading = ref(false);
const viewVisible = ref(false);
const viewFileList = ref([]);
const initialIndex = ref(0);

const handleUpload = (options) => {
  loading.value = true;
  AdminFileAPI.add(options.file)
    .then(({ data }) => {
      ElMessage.success(
        $t('common.message.success.general', {
          action: $t('common.action.upload'),
        }),
      );
      if (props.multiple) {
        imageList.value.push(data);
      } else {
        imageList.value = [data];
      }
    })
    .catch(() => {
      ElMessage.error(
        $t('common.message.failed.general', {
          action: $t('common.action.upload'),
        }),
      );
    })
    .finally(() => {
      loading.value = false;
    });
};

const handleOnExceed = (files) => {
  imageList.value = [];
  handleUpload({ file: files[0] });
};

// 删除图片
const handleRemove = (id) => {
  // 组件变量删除
  imageList.value = imageList.value.filter((item) => item.id !== id);
  // 后端记录删除
  AdminFileAPI.delete({ id: id });
};

// 预览图片
const handlePictureCardPreview = (url) => {
  viewFileList.value = imageList.value.map((file) => file.url);
  initialIndex.value = imageList.value.findIndex((file) => file.url === url);
  viewVisible.value = true;
};

// 关闭预览界面
const closePreview = () => {
  viewVisible.value = false;
};

// 关闭本组件界面
const closeUploadModal = () => {
  show.value = false;
  imageList.value = [];
  emit('reload');
};

/**
 * 暴露方法，显示对话框
 */
defineExpose({
  show() {
    show.value = true;
  },
});
</script>
